//
//  LcbAutomaticScrollView.m
//  huien
//
//  Created by yiban on 2017/5/26.
//  Copyright © 2017年 lcb. All rights reserved.
//

#import "LcbAutomaticScrollView.h"
#import "LcbImageView.h"
#import "NSObject+YBAdd.h"
@interface LcbAutomaticScrollView()
{
    CGFloat imageWidth;
    CGFloat imageHeight;
}
@property (strong, nonatomic) NSTimer *timer;
@end

@implementation LcbAutomaticScrollView


- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.needAutomaticScroll = YES;
        imageWidth = self.frame.size.width;
        imageHeight = self.frame.size.height;
        [self initScrollerView];
        [self initPageControl];
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickScrollView:)];
        [self.scrollView addGestureRecognizer:gesture];
        gesture = nil;//gestureRecognizer release
    }
    return self;
}

- (void)initScrollerView {
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, imageWidth, imageHeight)];
    self.scrollView.contentSize = CGSizeMake(imageWidth, imageHeight);
    self.scrollView.pagingEnabled = YES;
    self.scrollView.delegate = self;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.backgroundColor = UIColorFromRGB(0xf0f0f6);
    [self addSubview:self.scrollView];
}

- (void)initPageControl {
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(imageWidth - 100, imageHeight - 15, 80, 5)];
    self.pageControl.currentPageIndicatorTintColor = UIColorFromRGB(0xffffff);//UIColorFromRGB(0x00a5ed);
    self.pageControl.pageIndicatorTintColor =[UIColor colorWithWhite:1 alpha:0.5];
    self.pageControl.currentPage = 0;
    self.currentIndexImage = 0;
    [self.pageControl addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventValueChanged];
    [self addSubview:self.pageControl];
}

#pragma mark -点击白点回调
- (void)changePage:(UIPageControl *)sender {
    [self.timer invalidate];
    [self animationOfMove:sender.currentPage];
    //delegate
    if ([self.delegate respondsToSelector:@selector(tapPageControl)]) {
        [self.delegate tapPageControl];
    }
}

- (void)setImagesUrl:(NSMutableArray *)imagesUrl {
    _imagesUrl = imagesUrl;
    //根据image的数量设置contentSize
    self.scrollView.contentSize = CGSizeMake(imagesUrl.count *imageWidth , imageHeight);
    self.pageControl.numberOfPages = imagesUrl.count;
    [self createImageView];
}

- (void)setImages:(NSMutableArray *)images {
    _images = images;
    self.scrollView.contentSize = CGSizeMake(images.count *imageWidth , imageHeight);
    self.pageControl.numberOfPages = images.count;
    [self createImageView];
}

- (void)setPageControlInTheMiddle:(BOOL)pageControlInTheMiddle {
    _pageControlInTheMiddle = pageControlInTheMiddle;
    if (pageControlInTheMiddle == YES) {
        CGRect pageControFrame = self.pageControl.frame;
        pageControFrame.origin.x = (self.frame.size.width - pageControFrame.size.width) / 2;
        self.pageControl.frame = pageControFrame;
    }
}
//添加轮播的imageview
- (void)createImageView {
    //重新加载数据要清除之前的imageview和计时器，然后重新添加,否则添加一次数据重复添加一次view，定时器也会出错
    for (UIImageView *view in self.scrollView.subviews) {
        [view removeFromSuperview];
        if (self.timer) {
            [self.timer invalidate];
        }
    }
    
    for (int i = 0; i < self.imagesUrl.count; i ++) {
        
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.contentMode = UIViewContentModeScaleToFill;
        imageView.image = [UIImage imageNamed:@"app_detail_placeholder_large"];
        imageView.frame = CGRectMake(imageWidth * i, 0, imageWidth, imageHeight);
        //直接读取图片
        if (self.images.count > 0) {
            UIImage *image = [UIImage imageNamed:[self.images objectAtIndexCheck:i]];
            imageView.image = image;
        }
        //用url加载
        else if (self.imagesUrl.count > 0) {
            [imageView lcb_imageWithUrlStr:[self.imagesUrl objectAtIndexCheck:i] placeholder:[UIImage imageNamed:@"app_detail_placeholder_large"]];
        }
        
        [self.scrollView addSubview:imageView];
    }
    if (self.needAutomaticScroll) {
        [self addTimer];
    }
}

#pragma mark -点击imageView
- (void)clickScrollView:(UITapGestureRecognizer *)gesture {
    if ([self.delegate respondsToSelector:@selector(tapScrollView)]) {
        [self.delegate tapScrollView];
    }
    if ([self.delegate respondsToSelector:@selector(tapScrollView:)]) {
        [self.delegate tapScrollView:self.currentIndexImage];
    }
}

//计时器
- (void)addTimer {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    
    NSInteger second = 0;
    if (self.timeInterval != 0) {
        second = self.timeInterval;
    } else {
        second = 3;
    }
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:second target:self selector:@selector(showNextImage) userInfo:nil repeats:YES];
}

- (void)showNextImage {
    NSInteger page = self.pageControl.currentPage;
    if (page == self.imagesUrl.count - 1) {
        page = 0;
    } else {
        page ++;
    }
    [self animationOfMove:page];
}

//移动到指定页的动画
- (void)animationOfMove:(NSInteger)page {
    CGFloat offsetX = page * imageWidth;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];//匀速
    
    self.scrollView.contentOffset = CGPointMake(offsetX, 0);
    
    [UIView commitAnimations];
}

#pragma mark -scrllview delegate
//手指开始拖拽时
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    //停止计时器
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

//手指拖拽完毕 启动计时器
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (self.needAutomaticScroll) {
        [self addTimer];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    self.pageControl.currentPage = scrollView.contentOffset.x / imageWidth;
    self.currentIndexImage = (NSUInteger)self.pageControl.currentPage;
}
-(void)dealloc
{
    [LcbLog log:@"automaticscrollview--------->dealloc"];
}
@end
